package com.secsys.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.secsys.dto.MenuDTO;
import com.secsys.dto.RoleDTO;
import com.secsys.dto.SysUserDTO;
import com.secsys.model.TbSysLog;
import com.secsys.model.TbSysRole;
import com.secsys.model.TbSysUser;
import com.secsys.service.impl.LogServiceImpl;
import com.secsys.service.impl.RoleServiceImpl;
import com.secsys.service.impl.UserServiceImpl;
import com.secsys.util.Assisant;
import com.secsys.util.Constant;
import com.secsys.util.DateFormatUtils;
import com.secsys.util.MenuUtil;
import com.secsys.util.SystemUtils;

/**
 * @Description 系统用户控制类实现
 * @author LiusQ
 * @Date 2011-3-30 16:57
 * 
 */

public class UserAction extends BaseAction<SysUserDTO> {

	private SysUserDTO userDTO;
	
	private UserServiceImpl userService;
	
	private RoleServiceImpl roleService;
	
	private LogServiceImpl logService;
	
	private List<SysUserDTO> userList;
	
	private List<RoleDTO> roleList;
	
	private TbSysRole sysRole;
	
	private Integer userId;
	
	private final static Logger logger = Logger.getLogger(UserAction.class);

	public SysUserDTO getUserDTO() {
		return userDTO;
	}

	public void setUserDTO(SysUserDTO userDTO) {
		this.userDTO = userDTO;
	}

	public UserServiceImpl getUserService() {
		return userService;
	}

	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}

	/**
	 * @Description 用户简单注册信息处理
	 * @return
	 * @throws Exception
	 */
	public String register() throws Exception {
		System.err.println("用户注册");
		System.out.println(userDTO.getUserName());
		String ValidateCode=(String)ServletActionContext.getRequest().getSession().getAttribute("ValidateCode");
    	String validateCode=(String)ServletActionContext.getRequest().getSession().getAttribute("validateCode");
    	if (!ValidateCode.equals(validateCode)) {
			this.addFieldError("validateCode","验证码错误！");
			return "register"; 
		}
		
		
		userDTO.setLevel(new Integer(1)); // 注册用户设置为1级
		Date registerTemp = new Date(); // 产生一个时间
		Date registerTiem = DateFormatUtils
				.convertStringToDateTime(DateFormatUtils
						.convertDateTimeToString(registerTemp));
		userDTO.setRegisterTime(registerTiem);
		userDTO.setUserStatue("SOA");
		userDTO.setSex("保密");
        
		HttpServletRequest request = ServletActionContext.getRequest();
		System.out.println(request.getRemoteAddr());
		String registerAddr = SystemUtils.getRemoteHost(request);
		userDTO.setRegisterAddr(registerAddr);
		System.out.println("注册地址：" + registerAddr);
		TbSysUser tbSysUser=userService.queryUserByEmail(userDTO.getEmail());
		boolean flag=false;
		if (null!=tbSysUser && !"".equals(tbSysUser)) {
			this.addFieldError("email","注册失败，该邮箱已被注册！");
			return "register";
		}else {
			flag= userService.register(userDTO);
			if (!flag) {
				this.addFieldError("failure","注册失败，请填写正确的注册信息！");
				return "register"; 
			}
		}
		return "reg_success";
	}

	/**
	 * @Description 用户登录
	 * @return 返回成功"success",失败"failure"
	 * @throws Exception
	 */
	public String login() throws Exception {
		System.out.println(userDTO.getPassword() + ":" + userDTO.getUserName());
		TbSysUser userDto = userService.login(userDTO.getPassword(), userDTO
				.getUserName());
		// System.out.println(userDto.getTbSysRole().getRole());
		String uri = null;
		String msg = null;
		String urlMsg = null;
		List<MenuDTO> menuList = null;
		if (userDto != null) { // 登录成功保存用户信息
			//System.out.println(userDto.getTbSysRole().getTbSysRoleResources()
				//	.size());
			MenuUtil menuUtil = new MenuUtil();
			session.put("userDto", userDto); // 保存用户信息到session
			logger.info(userDto.getUserName() + " 用户已登录" + new Date());
			if(userDto.getTbSysRole()!=null){
			menuList = menuUtil.initSortMenu(userDto.getTbSysRole()
					.getTbSysRoleResources());
			session.put("menuList", menuList); // 将菜单信息资源存放到menuList中
			
			}
			System.out.println(userDto.getTbSysRole());
			System.out.println(userDto.getTbSysRole().getRole());
			if (userDto.getTbSysRole().getRole().equals(Constant.ADMIN)
					|| userDto.getTbSysRole().getRole().equals(
							Constant.BBS_SUPER_MANAGER)
					|| userDto.getTbSysRole().getRole().equals(
							Constant.BBS_MANAGER)) { // 判断是否为系统管理员、论坛版主
				return "manager";
			} else {
				msg = "欢迎你回来," + userDto.getUserName();
				uri = ServletActionContext.getRequest().getHeader("referer");

				if (uri.contains(Constant.BBS_LOGIN_URI)) {
					uri = "." + Constant.BBS_INDEX_URI;
					msg += "，现在将跳转到论坛首页。";
				} else {
					msg += "， 现在将转入登录前页面";
				}
				// session.put("historyUri", uri);
				urlMsg = "5秒钟后，浏览器将自动跳转到登录前页面";
			}
		} else { // 失败返回提示页面
			msg = "对不起，你输入的用户名或密码不正确";
			uri = Constant.BBS_LOGIN_URI;
			urlMsg = "5秒钟后，浏览器将自动跳转到登录页面";
		}
		String url = Assisant.autoMatchURL(uri, urlMsg);
		session.put("msg", msg);
		session.put("url", url);
		return "msg";
	}
	
	/**
	 * 查找用户列表
	 * @return
	 */
	public String listUser(){
		roleList = roleService.listRole();
		userList = userService.listUser();
		
		return "listUser";
	}

	/**
	 * 
	 * @Description 通过ID查询用户基本信息
	 * @return
	 * @throws Exception
	 */
	public String queryUserInfoById() throws Exception {

		session.put("user", "userDto");
		return "queryUserInfo";

	}
	
	
	/**
	 * 查看用户具体信息
	 * @return
	 */
	public String showUser() throws Exception {
		userDTO = userService.showUser(userId);
		if(String.valueOf(userDTO.getRoleId())!="" && String.valueOf(userDTO.getRoleId())!= null){
			sysRole = roleService.findById(userDTO.getRoleId());
		}
		return "showUser";
	}
	
	/**
	 * 创建用户添加界面
	 * @return
	 */
	public String createUserAddUI() throws Exception {
		
		roleList = roleService.listRole();
		return "createUserAddUI";
	}
	
	/**
	 * 创建用户修改页面
	 * @return
	 */
	public String createUserUpdate(){
		userDTO = userService.showUser(userId);
		if(String.valueOf(userDTO.getRoleId())!="" && String.valueOf(userDTO.getRoleId())!= null){
			sysRole = roleService.findById(userDTO.getRoleId());
		}
		roleList = roleService.listRole();
		return "createUserUpdate";
	}
	
	/**
	 * 修改用户信息，并添加日志
	 * @return
	 */
	public String updateUser(){
		TbSysLog sysLog = new TbSysLog();
		sysLog.setOperation("修改 " + userDTO.getUserName() + " 用户。" );
		TbSysUser userDtoLog = (TbSysUser)session.get("userDto");
		sysLog.setOperationer(userDtoLog.getUserName());
		Date opTime = new Date(); 
		sysLog.setOpTime(opTime);
		TbSysUser userLog = userService.findById(userDTO.getId());
		StringBuffer remark = new StringBuffer();
		remark.append(userLog.getId());
		remark.append(",");
		remark.append(userLog.getUserName());
		remark.append(",");
		remark.append(userLog.getEmail());
		remark.append(",");
		remark.append(userLog.getMsn());
		remark.append(",");
		remark.append(userLog.getQq());
		remark.append(",");
		remark.append(userLog.getSex());
		remark.append(",");
		remark.append(userLog.getBrithday());
		remark.append(",");
		remark.append(userLog.getResume());
		remark.append(",");
		remark.append(userLog.getCompany());
		remark.append(",");
		remark.append(userLog.getCareer());
		remark.append(",");
		remark.append(userLog.getProvince());
		remark.append(",");
		remark.append(userLog.getCity());
		remark.append(",");
		remark.append(userLog.getLevel());
		remark.append(",");
		remark.append(userLog.getTbSysRole().getId());
		remark.append(",");
		remark.append(userLog.getPassword());
		remark.append(",");
		remark.append(userLog.getOnlineStatue());
		remark.append(",");
		remark.append(userLog.getRegisterAddr());
		remark.append(",");
		remark.append(userLog.getRegisterTime());
		remark.append(",");
		remark.append(userLog.getUserStatue());
		sysLog.setRemark(remark.toString());
		sysLog.setLogFlag(0);
		List<String> operationList = new ArrayList<String>();
		operationList.add("修改 " + userDTO.getUserName() + " 用户。");
		operationList.add("添加" + userDTO.getUserName() + " 用户。" );
		List<TbSysLog> logTest = logService.listInOperation(operationList);
		if(logTest!=null && logTest.size()>0){
			for(TbSysLog sysLogTest : logTest){
				sysLogTest.setLogFlag(3);
				logService.saveOrUpdate(sysLogTest);
			}
		}
		logService.addLog(sysLog);//插入日志
		userService.saveOrUpdate(userService.getBeanFromDTO(userDTO));
		request.put("successMsg", "修改用户成功");
		request.put("successUrl", "bbs/user/user_listUser.action");
		return "successMsg";
	}
	
	/**
	 * 后台添加用户信息
	 * @return
	 */
	public String userAdd() throws Exception {
		System.out.println("456" + userDTO.getUserName()+"123");
		System.out.println(userDTO.getEmail());
		if("".equals(userDTO.getUserName()) || userDTO.getUserName()==null){
			return "addInput";
		}
		if(userDTO.getLevel()==null || userDTO.getLevel()==0){
			return "addInput";
		}
		if("".equals(userDTO.getEmail()) || userDTO.getEmail()==null){
			return "addInput";
		}
		userDTO.setPassword("123456");
		userDTO.setUserStatue("SOA");
		Date registerTemp = new Date(); // 产生一个时间
		Date registerTiem = DateFormatUtils
				.convertStringToDateTime(DateFormatUtils
						.convertDateTimeToString(registerTemp));
		userDTO.setRegisterTime(registerTiem);
		HttpServletRequest requestTest = ServletActionContext.getRequest();
		System.out.println(requestTest.getRemoteAddr());
		System.out.println(userDTO.getRoleId());
		String registerAddr = SystemUtils.getRemoteHost(requestTest);
		userDTO.setRegisterAddr(registerAddr);
		
		userService.userAdd(userDTO);
		TbSysLog sysLog = new TbSysLog();
		sysLog.setOperation("添加" + userDTO.getUserName() + " 用户。" );
		TbSysUser userDto = (TbSysUser)session.get("userDto");
		sysLog.setOperationer(userDto.getUserName());
		Date opTime = new Date(); 
		sysLog.setOpTime(opTime);
		String remark = userService.findUserInfoByName(userDTO.getUserName()).getId().toString();
		sysLog.setRemark(remark);
		sysLog.setLogFlag(0);
		List<String> operationList = new ArrayList<String>();
		operationList.add("修改 " + userDTO.getUserName() + " 用户。");
		operationList.add("添加" + userDTO.getUserName() + " 用户。" );
		List<TbSysLog> logTest = logService.listInOperation(operationList);
		if(logTest!=null && logTest.size()>0){
			for(TbSysLog sysLogTest : logTest){
				sysLogTest.setLogFlag(3);
				logService.saveOrUpdate(sysLogTest);
			}
		}
		logService.addLog(sysLog);//插入日志
		request.put("successMsg", "添加用户成功,初始密码为：123456.请及时修改。");
		request.put("successUrl", "bbs/user/user_listUser.action");
		return "successMsg";
	}
	@Override
	public SysUserDTO getModel() {
		userDTO = new SysUserDTO();
		return userDTO;
	}

	public List<SysUserDTO> getUserList() {
		return userList;
	}

	public void setUserList(List<SysUserDTO> userList) {
		this.userList = userList;
	}

	public RoleServiceImpl getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleServiceImpl roleService) {
		this.roleService = roleService;
	}

	public List<RoleDTO> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<RoleDTO> roleList) {
		this.roleList = roleList;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public LogServiceImpl getLogService() {
		return logService;
	}

	public void setLogService(LogServiceImpl logService) {
		this.logService = logService;
	}

	public TbSysRole getSysRole() {
		return sysRole;
	}

	public void setSysRole(TbSysRole sysRole) {
		this.sysRole = sysRole;
	}

}
